﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Top.Web;
using Top.Web.Api;
using Top.Web.Api.Filters;
using Top.Core;
using Top.PointStore.Business;
using Top.PointStore.Business.Models;
using Top.PointStore.Web.Filters;
//using Top.PointStore.Filters;


namespace Top.PointStore.Controllers
{
    /// <summary>商品兑换
    /// </summary>
    [Provider]
    public class ProductsExchangeController : ApiBase
    {
        //
        // GET: /ProductsExchange/

        #region admin
        public object GetExchangeState()
        {
            if (!User.IsAuthenticated)
            {
                throw new WebApiException(ExceptionCode.NotLogin, "请先登录");
            }
            var list = new List<dropdownlist>();
            list.Add(new dropdownlist()
            {
                key = "1",
                value = "待审核"
            });
            list.Add(new dropdownlist()
            {
                key = "2",
                value = "兑换处理中"
            });
            list.Add(new dropdownlist()
            {
                key = "3",
                value = "兑换成功"
            });
            list.Add(new dropdownlist()
            {
                key = "4",
                value = "审核未通过"
            });
            //list.Add(new dropdownlist()
            //{
            //    key = "5",
            //    value = "已使用"
            //});
            //list.Add(new dropdownlist()
            //{
            //    key = "6",
            //    value = "失效"
            //});
            //list.Add(new dropdownlist()
            //{
            //    key = "7",
            //    value = "已过期"
            //});
            //list.Add(new dropdownlist()
            //{
            //    key = "8",
            //    value = "已撤销"
            //});
            list.Add(new dropdownlist()
            {
                key = "9",
                value = "审核通过"
            });
            list.Add(new dropdownlist()
            {
                key = "10",
                value = "已发放"
            });
            return list;
        }

        [Login]
        public async Task<object> GetBrokerKidByList(int pageIndex = 1, int pageSize = 10)
        {
            var pager = Pager.Create(pageIndex, pageSize);
            return await ProductsExchangeManager.GetList(pager, User);
        }

        [Login]
        public async Task<object> GetList(int cityKid, int status = 0, int categoryKid = 0, string keyWords = "", string sdt = "", string edt = "", int pageIndex = 1, int pageSize = 10, int brokerKid = 0, int exchangeType = 0, string agentStores = "", string expandingHeader = "")
        {
            var pager = Pager.Create(pageIndex, pageSize);
            string orderNO = Get("orderNO", "");
            string productName = Get("productName", "");
            string brokerName = Get("brokerName", "");
            string brokerPhone = Get("brokerPhone", "");
            int lowPoint = Get("lowPoint", 0);
            int topPoint = Get("topPoint", 0);
            return await ProductsExchangeManager.GetList(cityKid, pUser.PointStoreAuth.F_CityKid, pager, status, categoryKid, sdt, edt, orderNO, productName, brokerName, brokerPhone, lowPoint, topPoint, exchangeType, agentStores, expandingHeader);
        }



        #endregion

        /// <summary>保存商品兑换信息
        /// </summary>
        /// <returns></returns>
        [Login]
        public async Task<object> Save(int kid, string uk, int productKid, int pointNum, int isStatus, string remark)
        {
            var model = new T_ProductsExchange_new();
            model.Kid = kid;
            model.F_UserToken = uk;
            model.F_ProductKid = productKid;
            model.F_ExchangeTime = DateTime.Now;
            model.F_PointNum = pointNum;
            model.F_IsStatus = isStatus;
            model.F_Remark = remark;

            var result = 0;
            if (model.Kid > 0)
            {
                result = await ProductsExchangeManager.Update(model);
            }
            else
            {
                result = await ProductsExchangeManager.Add(model);
            }
            switch (result)
            {
                case 0:
                    throw new WebApiException("更新失败");
                case -1:
                    throw new WebApiException("商品id有误");
                case -2:
                    throw new WebApiException("经纪人id有误");
                case -3:
                    throw new WebApiException("兑换记录状态有误");
                case -4:
                    throw new WebApiException("兑换记录id有误");
                default:
                    break;
            }
            return result;
        }

        /// <summary>获取经纪人的兑换记录(webapp调用)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [Login]
        public async Task<object> GetExchangeList(int pageIndex = 1, int pageSize = 20)
        {
            return await ProductsExchangeManager.GetList(Pager.Create(pageIndex, pageSize), User);
        }
        /// <summary>更改状态和备注
        /// </summary>
        /// <returns></returns>
        public async Task<object> UpdateState(int kid, int state, string time, string token, string remark = "")
        {
            CheckRequest(kid, time, token);
            return await ProductsExchangeManager.UpdateStateWithRemark(kid, (ExchangeState)state, remark);
        }

        private void CheckRequest(int kid, string time, string token)
        {
            if (kid <= 0)
                throw new WebApiException("订单编号不能为空");

            var now = DateTime.Now;
            if (string.IsNullOrEmpty(time))
                throw new WebApiException("时间不能为空");

            DateTime dateTime;
            if (!DateTime.TryParseExact(time, "yyyyMMddHHmmss", null, DateTimeStyles.None, out dateTime))
                throw new WebApiException("时间格式错误");

            var timeSpan = now.Subtract(dateTime).TotalMinutes;
            timeSpan = timeSpan > 0 ? timeSpan : -timeSpan;
            if (timeSpan > 5)
                throw new WebApiException("请求已过期");

            if (string.IsNullOrEmpty(token))
                throw new WebApiException("token不能为空");


            var guidToken2 = WebHelper.MD5(time + ProductsExchangeManager.Get(kid).Result.F_Guid);
            if (token != guidToken2)
                throw new WebApiException("token异常");
        }



        /// <summary>收获地址
        /// </summary>
        /// <param name="exchangeId"></param>
        /// <param name="consignee"></param>
        /// <param name="mobile"></param>
        /// <param name="companyname"></param>
        /// <param name="companyaddress"></param>
        /// <returns></returns>
        public async Task<int> ShipInfo(int exchangeId, string consignee, string mobile, string companyname, string companyaddress)
        {
            return await ProductsExchangeManager.ShipInfo(exchangeId, consignee, mobile, companyname, companyaddress);
        }

        /// <summary>撤销
        /// </summary>
        /// <returns></returns>
        [Login]
        public async Task<object> Revoke(int kid, string remark = "")
        {
            return await ProductsExchangeManager.Revoke(kid, (int)ExchangeState.Revoked, remark);
        }

        [Login]
        public async Task<int> Send(int kid, string customerName, DateTime orderTime, string productName, string phone)
        {
            return await ProductsExchangeManager.Send(kid, customerName, orderTime, productName, phone);
        }
        [Login]
        public object SendKids(string kids)
        {
            return ProductsExchangeManager.SendKids(kids);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="kid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [Login]
        public object Audit(int kid, int status)
        {
            Task<int> auditResult = ProductsExchangeManager.Audit(kid, status);
            return auditResult;
        }

        [Login]
        public object AuditKids(string kids, int status)
        {
            return ProductsExchangeManager.AuditKids(kids, status);
        }


        [Login]
        public object Edit(string kids, int status)
        {
            return ProductsExchangeManager.EditKids(kids, status);
        }

        [Login]
        public object GetDetail(int kid)
        {
            return ProductsExchangeManager.Get(kid);
        }


        /// <summary>
        /// 导出兑换记录列表
        /// </summary>
        /// <param name="status"></param>
        /// <param name="categoryKid"></param>
        /// <param name="keyWords"></param>
        /// <param name="sdt"></param>
        /// <param name="edt"></param>
        /// <param name="cityKid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [Login]
        public object Export(int cityKid, int status = 0, int categoryKid = 0, string keyWords = "", string sdt = "", string edt = "", int pageIndex = 1, int pageSize = 10, int brokerKid = 0, int exchangeType = 0, string agentStores = "", string expandingHeader = "")
        {
            var pager = Pager.Create(pageIndex, pageSize);

            string orderNO = Get("orderNO", "");
            string productName = Get("productName", "");
            string brokerName = Get("brokerName", "");
            string brokerPhone = Get("brokerPhone", "");
            int lowPoint = Get("lowPoint", 0);
            int topPoint = Get("topPoint", 0);
            return ProductsExchangeManager.Export(cityKid, pUser.PointStoreAuth.F_CityKid, pager, status, categoryKid, sdt, edt, orderNO, productName, brokerName, brokerPhone, lowPoint, topPoint, exchangeType, agentStores, expandingHeader);
        }

    }
}
